package ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.NonNull;

import com.example.localvideo.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import bean.VideoBean;
import utils.LogUtils;

//视频播放界面
public class VideoPlayerActivity extends BaseActivity implements View.OnClickListener{
    private static final String TAG = "VideoPlayerActivity  Log:";
    private static final int MSD_UPDATAE_SYSTEM_TIME = 0;
    private static final int MSG_UPDATA_PLAYINT_TIME = 1;


    private VideoView mVideoView;
    private Button btuPlay;
    private TextView tvTitle;
    private TextView tvSystemTime;
    private ImageView ivBattery;
    private BatteryBroadcastReceiver batteryBroadcastReceiver;
    private AudioManager systemAudioManager;
    private ImageView ivVolume;
    private SeekBar sbVolume;
    private int currentVolume;
    private TextView tvPlayTime;
    private TextView tvTotalTime;
    private SeekBar sbVideo;
    private Button btuReplay;
    private Button btuPre;
    private Button btuNext;
    private Button btuFull;
    private int myPosition;
    private ArrayList<VideoBean> mVideoList;
    private LinearLayout llTop;
    private LinearLayout llBottom;

    @Override
    public int getLayout() {
        return R.layout.activity_player;
    }

    @Override
    public void initView() {

        mVideoView = (VideoView) findViewById(R.id.vv);
        llTop = (LinearLayout)findViewById(R.id.ll_top);
        llBottom = (LinearLayout)findViewById(R.id.ll_bottom);
        //顶部栏
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvSystemTime = (TextView) findViewById(R.id.tv_system_time);
        ivBattery = (ImageView) findViewById(R.id.iv_battery);
        ivVolume = (ImageView)findViewById(R.id.topbar_iv_volume);
        sbVolume = (SeekBar) findViewById(R.id.sb_volume);
        //底部栏
        btuPlay = (Button)findViewById(R.id.bottombar_btu_paly);
        tvPlayTime = (TextView)findViewById(R.id.tv_play_time);
        tvTotalTime = (TextView)findViewById(R.id.tv_play_total);
        sbVideo = (SeekBar)findViewById(R.id.sb_video);
        btuReplay = (Button)findViewById(R.id.bottom_btu_replay);
        btuPre = (Button)findViewById(R.id.bottom_btu_pre);
        btuNext = (Button)findViewById(R.id.bottom_btu_next);
        btuFull = (Button)findViewById(R.id.bottom_btu_full);
        //控制栏


//        MediaController mc = new MediaController(this);
//        mc.setAnchorView(mVideoView);
//        mVideoView.setMediaController(mc);
    }

    @Override
    public void initData() {
        updataSystemTime();//系统时间更新
        //注册电池电量的广播接受者(别忘记销毁了
        batteryBroadcastReceiver = new BatteryBroadcastReceiver();
        //创建电池电量变化的过滤器
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryBroadcastReceiver,filter);
        //获取声音管理器
        systemAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);//获取最大音量并设置给seekbar
        int maxVolume = systemAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        sbVolume.setMax(maxVolume);
        int nowVolume = systemAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);//获取当前音量
        sbVolume.setProgress(1);

    }

    @Override
    protected void onDestroy() {
        //销毁前要先移除handler里面的消息
        myHander.removeCallbacksAndMessages(null);
        //销毁注册的广播
        unregisterReceiver(batteryBroadcastReceiver);
        super.onDestroy();

    }

    //刷新
    Handler myHander = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case MSD_UPDATAE_SYSTEM_TIME:
                    updataSystemTime();
                    break;
                case MSG_UPDATA_PLAYINT_TIME://正在播放的进度
                    updataPlayingTime();
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    public void initListener() {
        Intent intent = getIntent();
        mVideoList = (ArrayList<VideoBean>) intent.getSerializableExtra("list");
        myPosition = intent.getIntExtra("position",-1);
        final VideoBean videoBean = mVideoList.get(myPosition);
        LogUtils.e(TAG, mVideoList.toString());
        //uri
        String path = videoBean.getData();
        mVideoView.setVideoURI(Uri.parse(path));
        //视频准备完成后的监听
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mVideoView.start();
                //标题
                tvTitle.setText(videoBean.getTitle());
                //总时间
                String totoalTime = getTime(videoBean.getTime());
                tvTotalTime.setText(totoalTime);
                //time
                updataBtuPlay();//更新一下按钮

                //设置进度条的最大进度
                sbVideo.setMax(videoBean.getTime());
                //初始化视频已播放时间
                updataPlayingTime();
            }
        });

        //视频播放完毕后的监听
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                myHander.removeMessages(MSG_UPDATA_PLAYINT_TIME);

                updataBtuPlay();
            }
        });

        //顶部栏
        sbVolume.setOnSeekBarChangeListener(new SeekBarChangeListener());
        ivVolume.setOnClickListener(this);
        //底部栏
        btuPlay.setOnClickListener(this);
        sbVideo.setOnSeekBarChangeListener(new SeekBarChangeListener());
        btuReplay.setOnClickListener(this);
        btuPre.setOnClickListener(this);
        btuNext.setOnClickListener(this);
        btuFull.setOnClickListener(this);

    }
    //按钮(记得设置监听，老毛病了
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bottombar_btu_paly:
                switchPlay();
                updataBtuPlay();
                break;
            case R.id.topbar_iv_volume:
                LogUtils.e(TAG,"点击了静音");
                updataBtuVolume();
                updataPlayingTime();
                break;
            case R.id.bottom_btu_replay:
                mVideoView.seekTo(0);
                sbVideo.setProgress(0);
            break;
            case R.id.bottom_btu_pre:
                if (myPosition !=0){
                    myPosition--;
                    VideoBean videoBeanp = mVideoList.get(myPosition);
                    String path = videoBeanp.getData();
                    mVideoView.setVideoURI(Uri.parse(path));
                }else {//第一个了还想点，那就换到最后一个
                    Toast.makeText(this,"已经是第一个了，自动为你跳转到最后一个",Toast.LENGTH_SHORT).show();
                    myPosition = mVideoList.size()-1;
                    VideoBean videoBeanp = mVideoList.get(myPosition);
                    String path = videoBeanp.getData();
                    mVideoView.setVideoURI(Uri.parse(path));
                }
                break;
            case R.id.bottom_btu_next:
                if (myPosition !=mVideoList.size()-1){
                    myPosition++;
                    VideoBean videoBeanp = mVideoList.get(myPosition);
                    String path = videoBeanp.getData();
                    mVideoView.setVideoURI(Uri.parse(path));
                }else {//最后一个还点下一个
                    myPosition = 0;
                    Toast.makeText(this,"已经是最后个了，自动为你跳转到第一个",Toast.LENGTH_SHORT).show();
                    VideoBean videoBeanp = mVideoList.get(myPosition);
                    String path = videoBeanp.getData();
                    mVideoView.setVideoURI(Uri.parse(path));
                }
                break;
            case R.id.bottom_btu_full:
                swichBar();
                break;
            default:
                break;
        }
    }
    private boolean bShowing =true;
//切换隐藏控制栏
    private void swichBar() {
        if (bShowing){
            //隐藏
//            new ViewPropertAnimator()
        }else {
            //显示
        }
    }

    //更新已播放时间
    private void updataPlayingTime() {
        //获取视频当前的播放时间
        int playProgressTime = mVideoView.getCurrentPosition();
        updatatime1(playProgressTime);
        myHander.sendEmptyMessageDelayed(MSG_UPDATA_PLAYINT_TIME,500);
    }

    private void updatatime1(int playProgressTime) {
        String ppt = getTime(playProgressTime);
        tvPlayTime.setText(ppt);
        //设置进度条位置
        sbVideo.setProgress(playProgressTime);

    }

    //静音按钮
    private void updataBtuVolume() {
        int now = systemAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);//获取当前音量，当再次点击的时候就恢复到这个音量
        if (now==0){
            systemAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,currentVolume,0);
            sbVolume.setProgress(currentVolume);
            changBtuVolume();
        }else {
            //保存当前音量，等解除静音的时候用
            currentVolume = systemAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);//记录当前音量
            systemAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,0,0);
            sbVolume.setProgress(0);
            changBtuVolume();
        }
    }
//根据当前的音量调整音量图案
    private void changBtuVolume(){
        int now = systemAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);//获取当前音量，当再次点击的时候就恢复到这个音量
        if(now == 0){
            ivVolume.setImageResource(R.drawable.volumeclose);
        }else {
            ivVolume.setImageResource(R.drawable.volume);
        }
    }

    //视频播放暂停
    private void switchPlay() {
        if (mVideoView.isPlaying()){
            mVideoView.pause();
        }else {
            mVideoView.start();
        }
    }
    //更新播放按钮的图片
    private void updataBtuPlay(){
        if (mVideoView.isPlaying()){
            btuPlay.setBackgroundResource(R.drawable.pause);
            //发送已播放消息
            myHander.sendEmptyMessageDelayed(MSG_UPDATA_PLAYINT_TIME,500);
        }else {
            btuPlay.setBackgroundResource(R.drawable.start);
            //移除发送消息
            myHander.removeMessages(MSG_UPDATA_PLAYINT_TIME);
        }
    }


    //更新系统时间
    private void updataSystemTime(){
        SimpleDateFormat spfrom = new SimpleDateFormat("HH:mm:ss");
        String systemTime = spfrom.format(new Date());
        tvSystemTime.setText(systemTime);
        //发送更新系统时间的消息
        myHander.sendEmptyMessageDelayed(MSD_UPDATAE_SYSTEM_TIME,500);//高于1000的话会有延迟
    }
//电池电量广播接受者
    private class BatteryBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //获取电池电量的等级
            int level = intent.getIntExtra("level",-1);
            LogUtils.e(TAG,"level:"+level);
            //更新电池图案
            updataImageBattery(level);
        }
    }
    //更新电池
    private void updataImageBattery(int level) {
        if(level>=80){
            ivBattery.setImageResource(R.drawable.electricfull);
        }else if(level>30 && level<80){
            ivBattery.setImageResource(R.drawable.electrichalf);
        }else {
            ivBattery.setImageResource(R.drawable.electriclow);
        }
    }

    //获取时间
    private String getTime(int gettime){
        String showTime;
        final int HOUR = 60*60*1000;
        final int MIN = 60*1000;
        final int SEC = 1000;
        int time = gettime;
        int hour = time / HOUR;
        int min = time % HOUR / MIN;
        int sec = time %MIN /SEC;
        if (hour >=1){//00:00:00
            showTime =  String.format("%02d:%02d:%02d",hour,min,sec);
        }else{//00:00
            showTime =  String.format("%02d:%02d",min,sec);
        }
        return showTime;
    }

//进度条事件监听(同时解决两个
    private class SeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {
        //进度发生变化时调用
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            switch (seekBar.getId()){
                case R.id.sb_volume:
                    systemAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress,0);//第三个代表是否显示系统的音量的控制面板,0为不显示，测试用
                    break;
                case R.id.sb_video:
//                    mVideoView.seekTo(progress);
                    break;
                default:
                    break;
            }

        }
        //手指按下时
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            switch (seekBar.getId()){
                case R.id.sb_volume:

                    break;
                case R.id.sb_video:
                    mVideoView.pause();//用户想动的时候先停一下
                    updataBtuPlay();
                    break;
                default:
                    break;
            }
        }
        //手指松开时
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            switch (seekBar.getId()){
                case R.id.sb_volume:
                    changBtuVolume();//如果手动拉到0的话就要改变一下图案
                    break;
                case R.id.sb_video:
                    int sfejife = seekBar.getProgress();
                    updatatime1(sfejife);
                    String dkdjfie ="当前进度"+getTime(seekBar.getProgress());
                    LogUtils.e(TAG,dkdjfie);
                    mVideoView.seekTo(sfejife);
                    mVideoView.start();
                    updataBtuPlay();
                    break;
                 default:
                     break;
            }


        }
    }
}
